#!/usr/bin/python

# Python string examples
s = 'spam'
print(s)

# Length of string
print(len(s))

# Index and Reverse Index
print s[-1]==s[len(s)-1]
print(s[0], s[1], s[2], s[3])
print(s[-1], s[-2], s[-3], s[-4])
for i in range(len(s)):
	print("s[" + str(i) + "] = " + s[i])
for i in range(-1, -5, -1):
	print("s[" + str(i) + "] = " + s[i])

# Slice, s[begin:non-inc-end]
p="0123456789"
print("p = " + p)
print("p[1:3] = " + p[1:3])
print("p[0:9999] = ", p[0:9999])
print("p[5:-1] = ", p[5:-1])
# Default slice: begin = 0, non-inc-end = len()
print("p[:] = ", p[:])
print("p[0:len(p)] = ", p[0:len(p)])
print("p[0:] = ", p[0:])
print("p[:len(p)] = ", p[:len(p)])
print("p[:3] = ", p[:3])
print("p[-2:] = ", p[-2:])

def prefix(x, sz):
	return x[:sz]
def suffix(x, sz):
	return x[-sz:]
	
print(prefix(p, 4) == p[:4])
print(suffix(p, 5) == p[-5:])

# Slice with step s[begin:non-inc-end:step]
print(p[0:len(p):1])
print(p[::1])

# Reverse String
print("reversed:")
print(''.join(reversed(p)))
print(p[::-1])


# Concatenation & Repeat
a='123'
b="456"
print("a = ", a, " b = ", b, " a + b = ", a+b)
print("a*4 = ", a*4)
print("2*b = ", 2*b)

# The type str are immutable.
try:
	print "a[0]='z'"
	a[0]='z'
except Exception, e:
	print e

# You should create new object
print a
a = 'z' + a[1:]
print a

# find & replace
a = 'a' + s[1:]
print a
print a.find('apa')
print a.find('m')
print a.find('zzz')
print a.replace('a','$')

# split
w = 'field 1;field 2;field 3'
print w
print w.split(';')

# upper & lower
c = "bLoNdE cAsE"
print c
print c.upper()
print c.lower()

# isalpha, isdigit, isspace
o='hello 123'
print o.isalpha(), o[:5].isalpha()
print o.isdigit(), o[-3:].isdigit()
print o.isspace(), o[5].isspace()

# lstrip, strip, rstrip
z='   ;;;hello world ;;; and ;; another;world;;;    '
print '[' + z + ']'
print '[' + z.lstrip() + ']'
print '[' + z.rstrip() + ']'
print '[' + z.strip() + ']'
print '[' + z.strip().strip(';') + ']'
e='\n\n\n\n\n\n\t\t\t\t\t      lala\t\t\t\t\t      \n\n\n\n\n\n'
print repr(e)
print e.strip()

# format expression and method
print 'int=%d, str=%s, float=%f' % (-9000, "superString", -0.51)
print "integer={0}, string={1}, float={2}".format(+100500, 'newFormatMethodPython2.6&3.0', 0.5)

# multiline string literal
l1='''Hello,
World! \'''
Hello """
'''
print l1
l2="""
Hi \""" '''
"""
print l2

# raw string literal (do not interpet \backslash)
rs = r'\t\n\r'
print repr(rs)
print rs

# unicode string
unic = u"Unicode String"
print type(unic), repr(unic), unic

# Note: In Python 2 all strings are 8bit by default and can be used as binary arrays (for example with files)
# In Python 3 all strings are Unicode by default and cannot be used as binaty arrays.
# In Python 3 for binary arrays you should use type "bytes" (for example with binary files).
# In any way you can use strings with text files in Python 2 and 3.

